package cn.chendd.example;

import junit.framework.TestCase;
import org.apache.commons.jci.ReloadingClassLoader;
import org.apache.commons.jci.listeners.ReloadingListener;
import org.apache.commons.jci.monitor.FilesystemAlterationMonitor;

import java.io.File;

/**
 * @author chendd
 * @date 2019/6/8 16:16
 * 监听文件（夹）变更事件
 */
public class ListenerDirectory extends TestCase {

    public void testListenerDirectory() throws Exception {

        ReloadingClassLoader classloader = new ReloadingClassLoader(this.getClass().getClassLoader());
        ReloadingListener listener = new ReloadingListener() {

            //-----------------------------文件夹监控---------------------------
            @Override
            public void onDirectoryCreate(File pDir) {
                System.out.println("文件夹创建 ：" + pDir.getAbsolutePath());
            }

            @Override
            public void onDirectoryChange(File pDir) {
                System.out.println("文件夹修改 ：" + pDir.getAbsolutePath());
            }

            @Override
            public void onDirectoryDelete(File pDir) {
                System.out.println("文件夹删除 ：" + pDir.getAbsolutePath());
            }
            //-----------------------------文件监控-----------------------------
            @Override
            public void onFileCreate(File pFile) {
                System.err.println("文件创建：" + pFile.getAbsolutePath());
            }

            @Override
            public void onFileChange(File pFile) {
                System.err.println("文件修改：" + pFile.getAbsolutePath());
            }

            @Override
            public void onFileDelete(File pFile) {
                System.err.println("文件删除：" + pFile.getAbsolutePath());
            }

        };
        listener.addReloadNotificationListener(classloader);
        File directory = new File("D:\\test\\logs");
        FilesystemAlterationMonitor fam = new FilesystemAlterationMonitor();
        fam.addListener(directory, listener);
        fam.setInterval(1000);//轮询检查事件
        fam.start();

        //没有别的用途，只是让程序不退出
        int index = 1;
        while(index < 50) {
            Thread.sleep(1000 * 2);
            index++;
        }
        fam.stop();
    }

}
